import 'dart:async';

import 'package:chewie/src/animated_play_pause.dart';
import 'package:chewie/src/chewie_player.dart';
import 'package:chewie/src/chewie_progress_colors.dart';
import 'package:chewie/src/cupertino/cupertino_progress_bar.dart';
import 'package:chewie/src/helpers/utils.dart';
import 'package:chewie/src/notifiers/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';

class VideoCustomControls extends StatefulWidget {
  VideoCustomControls(this.onBack, this.isLive,
      {Key? key, this.needShare = true})
      : super(key: key);
  final bool isLive;
  final Color backgroundColor = Color.fromRGBO(41, 41, 41, 0.7);
  final Color iconColor = Color.fromARGB(255, 200, 200, 200);
  final bool needShare;
  final void Function()? onBack;

  @override
  State<StatefulWidget> createState() {
    return _VideoCustomControlsState();
  }
}

class _VideoCustomControlsState extends State<VideoCustomControls>
    with SingleTickerProviderStateMixin {
  late PlayerNotifier notifier;
  late VideoPlayerValue _latestValue;
  double? _latestVolume;
  Timer? _hideTimer;
  final marginSize = 5.0;
  Timer? _expandCollapseTimer;
  Timer? _initTimer;
  bool _dragging = false;

  late VideoPlayerController controller;

  // We know that _chewieController is set in didChangeDependencies
  ChewieController get chewieController => _chewieController!;
  ChewieController? _chewieController;

  @override
  void initState() {
    super.initState();
    notifier = Provider.of<PlayerNotifier>(context, listen: false);
  }

  @override
  Widget build(BuildContext context) {
    //chewieController.videoPlayerController.value.errorDescription!
    if (_latestValue.hasError) {
      return Center(
        child: Icon(
          CupertinoIcons.exclamationmark_circle,
          color: Colors.white,
          size: 42,
        ),
      );
    }

    final backgroundColor = widget.backgroundColor;
    final iconColor = widget.iconColor;
    final orientation = MediaQuery.of(context).orientation;
    final barHeight = orientation == Orientation.portrait ? 30.0 : 47.0;
    final buttonPadding = orientation == Orientation.portrait ? 16.0 : 24.0;

    return MouseRegion(
      onHover: (_) => _cancelAndRestartTimer(),
      child: GestureDetector(
        onTap: ClickUtils.debounce(() => _cancelAndRestartTimer()),
        child: AbsorbPointer(
          absorbing: notifier.hideStuff,
          child: Stack(
            children: [
              if (_latestValue.isBuffering && !widget.isLive)
                const Center(
                  child: CircularProgressIndicator(),
                ),
              // else
              //   _buildHitArea(),
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  _buildTopBar(backgroundColor, iconColor, buttonPadding),
                  const Spacer(),
                  _buildBottomBar(backgroundColor, iconColor, 61),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _dispose();
    super.dispose();
  }

  void _dispose() {
    // controller.removeListener(_updateState);
    // controller.dispose();
    _hideTimer?.cancel();
    _expandCollapseTimer?.cancel();
    _initTimer?.cancel();
  }

  @override
  void didChangeDependencies() {
    final _oldController = _chewieController;
    _chewieController = ChewieController.of(context);
    controller = chewieController.videoPlayerController;

    if (_oldController != chewieController) {
      _dispose();
      _initialize();
    }

    super.didChangeDependencies();
  }

  Widget _buildBottomBar(
    Color backgroundColor,
    Color iconColor,
    double barHeight,
  ) {
    List<Widget> widgets = [];
    if (widget.isLive) {
      widgets = [
        // _buildPlayPause(controller, iconColor, barHeight),
        // _buildPosition(iconColor),
        // _buildProgressBar(),
        // _buildTime(iconColor),
        Spacer(),
        _buildExpandButton(backgroundColor, iconColor, barHeight),
      ];
    } else {
      widgets = [
        _buildPlayPause(controller, iconColor, barHeight),
        _buildPosition(iconColor),
        _buildProgressBar(),
        _buildTime(iconColor),
        _buildExpandButton(backgroundColor, iconColor, barHeight),
      ];
    }
    var container = SafeArea(
      top: false,
      bottom: chewieController.isFullScreen,
      child: AnimatedOpacity(
        opacity: notifier.hideStuff ? 0.0 : 1.0,
        duration: const Duration(milliseconds: 300),
        child: Container(
          height: barHeight,
          decoration: BoxDecoration(
              gradient: LinearGradient(
            colors: [
              Colors.black.withOpacity(0.5),
              Colors.black.withOpacity(0)
            ],
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
          )),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: widgets,
          ),
        ),
      ),
    );
    return Container(
      child: container,
    );
  }

  Widget _buildBackBTN() {
    var onback = widget.onBack;
    if (onback == null) {
      return Container();
    }
    return GestureDetector(
      onTap: ClickUtils.debounce(() {
        onback();
      }),
      child: AnimatedOpacity(
        opacity: notifier.hideStuff ? 0.0 : 1.0,
        duration: const Duration(milliseconds: 300),
        child: Container(
          width: 36,
          height: 36,
          child: Image.asset("assets/icons/video_back.png"),
        ),
      ),
    );
  }

  GestureDetector _buildShareBTN() {
    return GestureDetector(
      onTap: ClickUtils.debounce(() {}),
      child: AnimatedOpacity(
        opacity: notifier.hideStuff ? 0.0 : 1.0,
        duration: const Duration(milliseconds: 300),
        child: Container(
          width: 36,
          height: 36,
          child: Image.asset("assets/icons/video_share.png"),
        ),
      ),
    );
  }

  GestureDetector _buildExpandButton(
    Color backgroundColor,
    Color iconColor,
    double barHeight,
  ) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: _onExpandCollapse,
      child: AnimatedOpacity(
        opacity: notifier.hideStuff ? 0.0 : 1.0,
        duration: const Duration(milliseconds: 300),
        child: Container(
          height: barHeight,
          width: 44,

          // color: Colors.amber,
          padding: EdgeInsets.symmetric(horizontal: 5),
          child: Center(
            child: Icon(
              chewieController.isFullScreen
                  ? CupertinoIcons.arrow_down_right_arrow_up_left
                  : CupertinoIcons.arrow_up_left_arrow_down_right,
              color: iconColor,
              size: 16,
            ),
          ),
        ),
      ),
    );
  }

  GestureDetector _buildMuteButton(
    VideoPlayerController controller,
  ) {
    return GestureDetector(
      onTap: ClickUtils.debounce(() {
        _cancelAndRestartTimer();

        if (_latestValue.volume == 0) {
          controller.setVolume(_latestVolume ?? 0.5);
        } else {
          _latestVolume = controller.value.volume;
          controller.setVolume(0.0);
        }
      }),
      child: AnimatedOpacity(
        opacity: notifier.hideStuff ? 0.0 : 1.0,
        duration: const Duration(milliseconds: 300),
        child: Container(
          width: 36,
          height: 36,
          child: _latestValue.volume > 0
              ? Image.asset("assets/icons/video_voice.png")
              : Image.asset("assets/icons/video_mute.png"),
        ),
      ),
    );
  }

  GestureDetector _buildPlayPause(
    VideoPlayerController controller,
    Color iconColor,
    double barHeight,
  ) {
    return GestureDetector(
      onTap:  _playPause,
      child: Container(
        height: barHeight,
        color: Colors.transparent,
        padding: const EdgeInsets.only(
          left: 6.0,
          right: 6.0,
        ),
        child: AnimatedPlayPause(
          color: widget.iconColor,
          playing: controller.value.isPlaying,
        ),
      ),
    );
  }

  Widget _buildPosition(Color iconColor) {
    final position = _latestValue.position;

    return Padding(
      padding: const EdgeInsets.only(right: 12.0),
      child: Text(
        formatDuration(position),
        style: TextStyle(
          color: iconColor,
          fontSize: 12.0,
        ),
      ),
    );
  }

  Widget _buildTime(Color iconColor) {
    final position = _latestValue.duration;
    String time = formatDuration(position);
    if (time == '00:00') {
      time = '';
    }
    return Padding(
      padding: const EdgeInsets.only(right: 12.0),
      child: Text(
        time,
        style: TextStyle(
          color: iconColor,
          fontSize: 12.0,
        ),
      ),
    );
  }

  Widget _buildTopBar(
    Color backgroundColor,
    Color iconColor,
    double buttonPadding,
  ) {
    return Container(
      margin: EdgeInsets.only(
        top: marginSize,
        right: marginSize,
        left: marginSize,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _buildBackBTN(),
          const Spacer(),
          Column(
            children: [
              // _buildShareBTN(),
              _buildMuteButton(controller),
            ],
          ),
        ],
      ),
    );
  }

  void _cancelAndRestartTimer() {
    _hideTimer?.cancel();

    setState(() {
      notifier.hideStuff = false;

      _startHideTimer();
    });
  }

  Future<void> _initialize() async {
    controller.addListener(_updateState);

    _updateState();

    if (controller.value.isPlaying || chewieController.autoPlay) {
      _startHideTimer();
    }

    if (chewieController.showControlsOnInitialize) {
      _initTimer = Timer(const Duration(milliseconds: 200), () {
        setState(() {
          notifier.hideStuff = false;
        });
      });
    }
  }

  void _onExpandCollapse() {
    setState(() {
      notifier.hideStuff = true;
      // chewieController.deviceOrientationsAfterFullScreen = true;
      chewieController.toggleFullScreen();
      // SystemChrome.setPreferredOrientations(
      //     [DeviceOrientation.landscapeLeft]);
      // chewieController.enterFullScreen();

      _expandCollapseTimer = Timer(const Duration(milliseconds: 300), () {
        setState(() {
          _cancelAndRestartTimer();
        });
      });
    });
  }

  Widget _buildProgressBar() {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.only(right: 12.0),
        child: CupertinoVideoProgressBar(
          controller,
          onDragStart: () {
            setState(() {
              _dragging = true;
            });

            _hideTimer?.cancel();
          },
          onDragEnd: () {
            setState(() {
              _dragging = false;
            });

            _startHideTimer();
          },
          colors: ChewieProgressColors(
            playedColor: ThemeColor.primaryColor,
            handleColor: ThemeColor.primaryColor,
            bufferedColor: const Color.fromARGB(
              60,
              255,
              255,
              255,
            ),
            backgroundColor: const Color.fromARGB(
              20,
              255,
              255,
              255,
            ),
          ),
        ),
      ),
    );
  }

  void _playPause() {
    final isFinished = _latestValue.position >= _latestValue.duration;

    setState(() {
      if (controller.value.isPlaying) {
        notifier.hideStuff = false;
        _hideTimer?.cancel();
        controller.pause();
      } else {
        _cancelAndRestartTimer();

        if (!controller.value.isInitialized) {
          controller.initialize().then((_) {
            controller.play();
          });
        } else {
          if (isFinished) {
            controller.seekTo(const Duration());
          }
          controller.play();
        }
      }
    });
  }

  void _startHideTimer() {
    _hideTimer = Timer(const Duration(seconds: 3), () {
      setState(() {
        notifier.hideStuff = true;
      });
    });
  }

  void _updateState() {
    if (!mounted) return;
    setState(() {
      _latestValue = controller.value;
    });
  }
}
